<?php

namespace app\model\system;

use albert\traits\ModelTrait;
use app\model\BaseModel;

/**
 * 系统分组数据表 Model
 * Class SystemGroup
 * @package app\models\system
 */
class SystemGroup extends BaseModel
{
    use ModelTrait;

    /**
     * 初始化查询条件
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $where
     * @param null $model
     * @return SystemGroup|mixed
     */
    public static function initWhere($where, $model = null)
    {
        $model = $model ?? new self;
        if (isset($where['id']) && $where['id'] !== '') $model = $model->where('id', $where['id']);
        if (isset($where['config_name']) && $where['config_name'] !== '') $model = $model->where('config_name', $where['config_name']);
        return $model;
    }

    /**
     * 根据id获取当前记录中的fields值
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $id
     * @return array|mixed
     */
    public static function getField($id)
    {
        return json_decode(self::initWhere(['id' => $id])->value('fields'), true) ?: [];
    }

    /**
     * 处理分组字段
     * Author: Albert3306
     * Date: 2021/7/7
     * @param $field
     * @return array
     */
    public static function dealField($field): array
    {
        $data = [];
        if (isset($field['param'])) {
            $field['param'] = str_replace("\r\n", "\n", $field['param']); // 防止不兼容
            $params = explode("\n", $field['param']);
            if (is_array($params) && !empty($params)) {
                foreach ($params as $index => $v) {
                    $vl = explode('=>', $v);
                    if (isset($vl[0]) && isset($vl[1])) {
                        $data[$index]['value'] = $vl[0];
                        $data[$index]['label'] = $vl[1];
                    }
                }
            }
        }
        return $data;
    }
}